import time
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,redirect
from web.forms.project import ProjectModelForm
from web import models
from utils.tencent.cos import create_bucket


def project_list(request):
    if request.method == 'GET':
        # GET请求查看项目列表
        """
        1.从数据库中获取两部分数据
            我创建的所有项目：已星标、未星标
            我参与的所有项目：已星标、未星标

        2.把已星标数据提取出来：
            列表 = 循环【我创建的项目】 + 【我参与的所有项目】 
        得到三个列表：星标、创建、参与
        """
        # 我创建的所有项目
        # 去数据库中查询两次，这样查询的话效率低下，多了一次查询
        # not_star = models.Project.objects.filter(creator=request.saas.user,star=False)
        # star = models.Project.objects.filter(creator=request.saas.user,star=True)
        project_dict = {'star':[],'my':[],'join':[]}
        my_project_list = models.Project.objects.filter(creator=request.saas.user)
        for row in my_project_list:
            if row.star:
                project_dict['star'].append({'value':row,'type':'my'})
            else:
                project_dict['my'].append(row)

        # 我参与的所有项目
        join_project_list = models.ProjectUser.objects.filter(user=request.saas.user)
        for item in join_project_list:
            if item.star:
                # item.project保证project_dict中存储的都是project对象
                # project_dict['star'].append(item.project)
                project_dict['star'].append({'value':item.project,'type':'join'})
            else:
                project_dict['join'].append(item.project)

        form = ProjectModelForm(request)

        return render(request,'project_list.html',{'form':form,'project_dict':project_dict})

    # POST，对话框ajax添加项目
    form = ProjectModelForm(request,data=request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        # 1.为项目创建一个桶（桶命名规则不能出现汉字，可利用python汉字转拼音模块）
        bucket = "{}-{}-{}-1302101842".format(name,request.saas.user.mobile_phone, str(int(time.time())))
        region = 'ap-chengdu'
        create_bucket(bucket,region)

        # 表单验证通过:项目名、颜色、描述（默认只有这三项）+ creator谁创建的项目
        # 创建者等于登录用户(request.saas.user 中间件中已经定义过了)
        form.instance.creator = request.saas.user 
        form.instance.bucket = bucket
        form.instance.region = region
        # 2.创建项目(确保当前用户有无权限新建项目，以及是否还有额度)
        instance = form.save()

        # 3.项目初始化问题类型
        issues_type_object_list = []
        for item in models.IssuesType.PROJECT_INIT_LIST:  # ["任务", '功能', 'Bug']
            issues_type_object_list.append(models.IssuesType(project=instance, title=item))
        models.IssuesType.objects.bulk_create(issues_type_object_list)
        
        return JsonResponse({'status':True})
    # 表单验证未通过显示错误信息    
    return JsonResponse({'status':False,'error':form.errors})


def project_star(request,project_type,project_id):
    """项目星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id,creator=request.saas.user).update(star=True)
        return redirect('web:project_list')
    
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id,user=request.saas.user).update(star=True)
        return redirect('web:project_list')
    return HttpResponse('请求错误')

def project_unstar(request,project_type,project_id):
    """ 取消星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id,creator=request.saas.user).update(star=False)
        return redirect('web:project_list')
    
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id,user=request.saas.user).update(star=False)
        return redirect('web:project_list')
    return HttpResponse('请求错误')

